﻿<template>
  <div class="purchase-orders-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>采购订单</h3>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新建订单
          </el-button>
        </div>
      </template>

      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" clearable>
              <el-option 
                v-for="supplier in suppliers" 
                :key="supplier.id" 
                :label="supplier.name" 
                :value="supplier.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待确认" value="待确认" />
              <el-option label="已确认" value="已确认" />
              <el-option label="已发货" value="已发货" />
              <el-option label="部分入库" value="部分入库" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="supplierName" label="供应商" width="150">
          <template #default="{ row }">
            <div class="supplier-info">
              <div>{{ row.supplierName }}</div>
              <div class="supplier-rating">
                <el-rate 
                  v-model="row.supplierRating" 
                  disabled 
                  show-score 
                  text-color="#ff9900"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="expectedDate" label="预计到货" width="120" />
        <el-table-column label="操作" width="330" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === '待确认'" 
              type="success" 
              size="small" 
              @click="handleConfirm(row)"
            >
              确认
            </el-button>
            <el-button 
              v-if="['已确认', '部分入库'].includes(row.status)" 
              type="warning" 
              size="small" 
              @click="handleReceipt(row)"
            >
              入库
            </el-button>
            <el-button 
              v-if="['已确认'].includes(row.status)" 
              type="info" 
              size="small" 
              @click="handleShip(row)"
            >
              <el-icon><Goods /></el-icon>
              发货
            </el-button>
            <el-button 
              v-if="['待确认', '已确认'].includes(row.status)" 
              type="danger" 
              size="small" 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单表单抽屉 -->
    <OrderFormDrawer
      v-model="dialogVisible"
      :suppliers="suppliers"
      @submit="handleOrderSubmit"
      @close="handleDialogClose"
      ref="orderFormDrawerRef"
    />

    <el-dialog
      v-model="viewDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentOrder.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ currentOrder.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="预计到货">{{ currentOrder.expectedDate }}</el-descriptions-item>
          <el-descriptions-item label="采购员">{{ currentOrder.buyer }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentOrder.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>商品明细</el-divider>
        <el-table :data="currentOrder.products" border>
          <el-table-column prop="productCode" label="商品编码" width="120" />
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="specification" label="规格" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="{ row }">
              ¥{{ (row.quantity * row.unitPrice).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="600px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <el-input :value="currentOrder?.orderNo" disabled />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input :value="currentOrder?.supplierName" disabled />
        </el-form-item>
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰速运" value="顺丰速运" />
            <el-option label="圆通速递" value="圆通速递" />
            <el-option label="中通快递" value="中通快递" />
            <el-option label="韵达快递" value="韵达快递" />
            <el-option label="申通快递" value="申通快递" />
            <el-option label="京东物流" value="京东物流" />
            <el-option label="德邦物流" value="德邦物流" />
            <el-option label="其他物流" value="其他物流" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="发货备注">
          <el-input 
            v-model="shipForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入发货备注（选填）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitShip" :loading="submitLoading">
          确定发货
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, View, Goods } from '@element-plus/icons-vue'
import OrderFormDrawer from './components/OrderFormDrawer.vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const shipDialogVisible = ref(false)
const orderFormDrawerRef = ref()
const shipFormRef = ref()
const submitLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  supplierId: '',
  status: '',
  dateRange: []
})


// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 供应商数据
const suppliers = ref([
  { id: 1, name: '苹果供应商', code: 'S001' },
  { id: 2, name: '耐克供应商', code: 'S002' },
  { id: 3, name: '宜家供应商', code: 'S003' }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    orderNo: 'PO20240115001',
    supplierId: 1,
    supplierName: '苹果供应商',
    supplierRating: 4.5,
    totalAmount: 25000,
    status: '已确认',
    createTime: '2024-01-15 10:00:00',
    expectedDate: '2024-01-20',
    buyer: '张三',
    remark: '紧急采购',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        quantity: 5,
        unitPrice: 5000
      }
    ]
  },
  {
    id: 2,
    orderNo: 'PO20240115002',
    supplierId: 2,
    supplierName: '耐克供应商',
    supplierRating: 4.2,
    totalAmount: 12000,
    status: '待确认',
    createTime: '2024-01-15 14:00:00',
    expectedDate: '2024-01-25',
    buyer: '李四',
    remark: '',
    products: [
      {
        productCode: 'P003',
        productName: 'Nike运动鞋',
        specification: '42码 白色',
        unit: '双',
        quantity: 30,
        unitPrice: 400
      }
    ]
  }
])

const currentOrder = ref(null)

// 发货表单
const shipForm = reactive({
  logisticsCompany: '',
  trackingNo: '',
  remark: ''
})

// 发货表单验证规则
const shipRules = {
  logisticsCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    supplierId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const showAddDialog = () => {
  orderFormDrawerRef.value?.open()
}

const handleEdit = (row) => {
  orderFormDrawerRef.value?.open(row)
}

const handleView = (row) => {
  currentOrder.value = row
  viewDialogVisible.value = true
}

const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm('确定要确认该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已确认'
      ElMessage.success('订单确认成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleReceipt = (row) => {
  ElMessage.info('跳转到采购入库页面')
  // 这里可以跳转到采购入库页面，并传递订单信息
}

const handleShip = (row) => {
  currentOrder.value = row
  resetShipForm()
  shipDialogVisible.value = true
}

const handleSubmitShip = async () => {
  if (!shipFormRef.value) return

  try {
    await shipFormRef.value.validate()

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    const index = tableData.value.findIndex(item => item.id === currentOrder.value.id)
    if (index > -1) {
      tableData.value[index].status = '已发货'
      tableData.value[index].shipInfo = {
        logisticsCompany: shipForm.logisticsCompany,
        trackingNo: shipForm.trackingNo,
        shipTime: new Date().toLocaleString(),
        remark: shipForm.remark
      }
      ElMessage.success('发货成功')
    }

    shipDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('发货失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetShipForm = () => {
  Object.assign(shipForm, {
    logisticsCompany: '',
    trackingNo: '',
    remark: ''
  })
  shipFormRef.value?.clearValidate()
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已取消'
      ElMessage.success('订单取消成功')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

// 处理订单提交
const handleOrderSubmit = (orderData) => {
  if (orderData.id) {
    // 编辑订单
    const index = tableData.value.findIndex(item => item.id === orderData.id)
    if (index > -1) {
      tableData.value[index] = { 
        ...orderData,
        status: '待确认',
        createTime: new Date().toLocaleString()
      }
    }
  } else {
    // 新增订单
    const newOrder = {
      ...orderData,
      id: Date.now(),
      status: '待确认',
      createTime: new Date().toLocaleString()
    }
    tableData.value.unshift(newOrder)
  }
  loadData()
}


const getStatusType = (status) => {
  const statusMap = {
    '待确认': 'warning',
    '已确认': 'primary',
    '部分入库': 'info',
    '已发货': 'success',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}


const handleDialogClose = () => {
  // 抽屉关闭时的处理
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}


// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.purchase-orders-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.supplier-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.supplier-rating {
  font-size: 12px;
}
</style>
